package cn.sundat.web;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.junit.Test.None;

import com.opensymphony.xwork2.ActionSupport;

import cn.sundat.model.CompanyProduct;
import cn.sundat.model.FileBean;
import cn.sundat.service.CompanyProductService;

/**
 * 下载文件action
 * author LeeLiang
 */
public class DownloadAction extends ActionSupport{
	private String cp_id;
	
	public String getCp_id() {
		return cp_id;
	}
	public void setCp_id(String cp_id) {
		this.cp_id = cp_id;
	}
	
	@Resource(name="companyProductService")
	private CompanyProductService cpService;
	
	/**
	 * 单个文件下载
	 * @return
	 * @throws Exception
	 */
	public String down() throws Exception {
		//1.获取要下载的文件
			//前台参数传递的文件名
//			String cp_id = ServletActionContext.getRequest().getParameter("cp_id");
			CompanyProduct cp = cpService.getById(cp_id);
			String fileName = cp.getFile();
			//拼接为真实路径文件名
			String realPath = ServletActionContext.getServletContext().getRealPath("/plan");
			//要下载的文件
			File file = new File(realPath+"/"+fileName);
			if(!file.exists()) {
				ServletActionContext.getRequest().setAttribute("msg","文件丢失");
				return "msg";
			}
		//2.设置下载的响应头设置
			//设置下载的文件名
			int index = fileName.indexOf("-");
			String downName = fileName.substring(index+1);
			ServletActionContext.getResponse().setHeader("content-disposition", "attachment;filename="+new String(downName.getBytes("utf-8"), "iso8859-1"));
		//3.读取流
			FileInputStream is = new FileInputStream(file);
		//4.输出流
			ServletOutputStream os = ServletActionContext.getResponse().getOutputStream();
		//5.写出数据
			byte[] bys = new byte[1024];
			int len=0;
			while((len=is.read(bys))>0) {
				os.write(bys, 0, len);
			}
			//关闭流
			is.close();
			os.close();
		
		return NONE;
	}
	
	/**
	 * 多文件的下载 ，边压缩边下载.
	 * @return
	 */
	public String manyDown() {
		HttpServletResponse response = ServletActionContext.getResponse();
		//1.接收参数，封装成filebean对象集合
			String idStr = ServletActionContext.getRequest().getParameter("ids");
			String[] ids = idStr.split(",");
			System.out.println(ids.length);
			for (String string : ids) {
				System.out.println(string);
			}
			List<FileBean> fbList = new ArrayList<>();
			FileBean fb = null;
			for (String id : ids) {
				fb = new FileBean();
				CompanyProduct cp = cpService.getById(id);
				String filePath = cp.getFile();
				String fileName = filePath.substring(filePath.indexOf("-")+1);
				fb.setFileId(id);
				fb.setFilePath(filePath);
				fb.setFileName(fileName);
				fbList.add(fb);
			}
		//2.设置压缩头(解决不同浏览器压缩包因为中文名字出现的错误)
			String zipName = "download.zip";
			response.setContentType("APPLICATION/OCTET-STREAM");
			response.setHeader("Content-Disposition", "attachment; filename="+zipName);
			
			//设置压缩流：将response直接写入，边压缩边下载
			ZipOutputStream zipos = null;
			try {
				zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
				zipos.setMethod(ZipOutputStream.DEFLATED);//设置压缩方法
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		//3.循环将文件写入压缩流
			DataOutputStream os = null;
			for(int i=0;i<fbList.size();i++) {
				String fileName = fbList.get(i).getFileName();
				String filePath = fbList.get(i).getFilePath();
				
				String realPath = ServletActionContext.getServletContext().getRealPath("/plan");
				File file = new File(realPath+"/"+filePath);
				
				try {
					zipos.putNextEntry(new ZipEntry(i+fileName));
					os = new DataOutputStream(zipos);
					
					InputStream is = new FileInputStream(file);
					byte[] bys = new byte[1024];
					int len=0;
					while((len=is.read(bys))!=-1) {
						os.write(bys, 0, len);
					}
					is.close();
					zipos.closeEntry();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		//4.关闭流
		try {
			os.flush();
			os.close();
			zipos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return NONE;
	}
}
